import os
import cv2
import time
import numpy as np

# 图像和视频转换
def img_to_video(img_path,video_name):
    img_init = os.listdir(img_path)
    img_init.sort(key=lambda x: int(x[:-4]))

    img0 = cv2.imread(img_path + '/{}'.format(img_init[0]), flags=1)
    w=img0.shape[1]
    h=img0.shape[0]
    fps =25
    fourcc = cv2.VideoWriter_fourcc(*"mp4v")
    # videoWriter = cv2.VideoWriter("/home/ltt/2024_6/pips2_master/logs_demo/track4.mp4", fourcc, fps, (w, h))
    videoWriter = cv2.VideoWriter(video_name, fourcc, fps, (w, h))
    # for i in range(210):
    for i in range(len(img_init)):
        img = cv2.imread(img_path+'/{}'.format(img_init[i]),flags=1) #使用opencv读取图像，直接返回numpy.ndarray 对象，通道顺序为BGR ，注意是BGR，通道值默认范围0-255。
        videoWriter.write(img)
    videoWriter.release() #释放
    cv2.destroyAllWindows()
    return fps


#单目视频
def vedio_image_sig(video_path,output_imgs):#双目视频分解
    cap = cv2.VideoCapture(video_path)
    count = 0
    while cap.isOpened():
        ret, frame = cap.read()
        count += 1
        print(count)
        if ret:
            # cv2.namedWindow("0", cv2.WINDOW_NORMAL)
            # cv2.imshow("0", frame)
            # cv2.waitKey(1)
            # if count>=0:
                # if count<529:
            cv2.imwrite(os.path.join(output_imgs, f'{count:05}.png'),frame)
        else:
            print(count)
            break
    # cap.release()
    # cv2.destroyAllWindows()


def vedio_image(video_path,output_imgs):#双目视频分解
    cap = cv2.VideoCapture(video_path)
    count = 0
    while cap.isOpened():
        ret, frame = cap.read()
        print(count)
        if ret:
            count += 1
            h, w, _ = frame.shape
            a=int(h/2)
            frame = frame[:a, :, :]
            # split the whole image as two
            cv2.imwrite(os.path.join(output_imgs, f'{count:05}.png'), frame)
        else:
            break
    cap.release()

    cv2.destroyAllWindows()

def vedio_image_s(video_path,output_imgs):#双目视频分解
    cap = cv2.VideoCapture(video_path)
    count = 0
    while cap.isOpened():
        ret, frame = cap.read()
        print(count)
        if ret:
            count += 1
            h, w, _ = frame.shape

            a=int(w/2)
            # frame = frame[:a, :, :]
            frame = frame[ :,:a, :]
            # frame = frame[:, :, :]
            # split the whole image as two
            cv2.imwrite(os.path.join(output_imgs, f'{count:05}.png'), frame)
        else:
            break
    cap.release()
    cv2.destroyAllWindows()


import cv2
import os



# open the video file
def sll_vediotoimg(video_path,output_left,output_right):
    cap = cv2.VideoCapture(video_path)
    count = 0
    while cap.isOpened():
        ret, frame = cap.read()
        print(count)
        if ret:
            count += 1
            if count < 150:
                h, w, _ = frame.shape
                right_frame = frame[::2, :, :]
                left_frame = frame[1::2, :, :]

                # split the whole image as two
                cv2.imwrite(os.path.join(output_left, f'{count:05}.png'), left_frame)
                cv2.imwrite(os.path.join(output_right, f'{count:05}.png'), right_frame)
        else:
            break
    # release the resource
    cap.release()
    cv2.destroyAllWindows()

def avi_to_images(video_path, output_folder):
    # 检查输出文件夹是否存在，不存在则创建
    if not os.path.exists(output_folder):
        os.makedirs(output_folder)
    # 打开视频文件
    cap = cv2.VideoCapture(video_path)
    # 检查视频是否打开成功
    if not cap.isOpened():
        print("Error: Cannot open video file.")
        return
    frame_count = 0
    while True:
        ret, frame = cap.read()  # 读取一帧
        if not ret:
            break  # 如果无法读取帧，结束循环
        # 构建图片文件名
        frame=frame[ :,-600:, :]
        image_filename = f"{output_folder}/{frame_count:05}.png"
        # cv2.imwrite(os.path.join(output_imgs, f'{count:05}.png'), frame)
        # 保存帧为图片
        cv2.imwrite(image_filename, frame)
        print(f"Saved: {image_filename}")
        frame_count += 1
    # 释放视频对象
    cap.release()
    print("Done converting video to images.")


if __name__ == '__main__':
    # img_path="/home/ltt/point_track/changzheng/track/"
    # # "/big_data/zjy/instruments/images/train/007001.jpg"
    img_path='/big_data/ltt/MICCAI/d1k1_left_image/'
    video_name="/home/ltt/point_track/miccai.mp4"
    img_to_video(img_path,video_name)

    # video_path="/data_big/ltt/STIRD/STIRDataset/25/left/seq15/frames/00099160ms-00103280ms-visible.mp4"
    # output_imgs ="/data_big/ltt/STIRD/25/left/seq15/frames"
    # # # output_imgs ="/home/ltt/point_track/instrument"
    # if not os.path.exists(output_imgs):
    #     os.makedirs(output_imgs)
    # vedio_image_sig(video_path, output_imgs)

    # video_path ="/home/ltt/point_track/rot_img/hamlyn_left_rotate.avi"
    # target_base_dir ="/home/ltt/point_track/rot_img/hamlyn_left_rotate/"
    # avi_to_images(video_path, target_base_dir)

    # img_path="/home/ltt/2024_6/pips2_master/logs_demo/track4/"
    # img_to_video(img_path)

    # 源目录和目标基目录
    base_dir = "/data_big/ltt/STIRD"

    # 遍历 01 到 29
    for num in range(2, 30):
        source_base_dir = os.path.join(base_dir, "STIRDataset", f"{num:02d}", "left")
        target_base_dir = os.path.join(base_dir, "STIR_img", f"{num:02d}", "left")

        if os.path.exists(source_base_dir ):
            seq_dirs = [d for d in os.listdir(source_base_dir ) if
                        d.startswith("seq") and os.path.isdir(os.path.join(source_base_dir, d))]
            num_seq_dirs = len(seq_dirs)
        else:
            num_seq_dirs = 0
        print("seq_dirs is",num_seq_dirs)

        # 遍历 seq00 到 seq99
        for i in range(num_seq_dirs):
            seq_dir = f"seq{i:02d}"
            source_dir = os.path.join(source_base_dir, seq_dir, "frames")
            # 检查源目录是否存在
            if not os.path.exists(source_dir):
                continue
            # 遍历源目录中的所有文件
            for filename in os.listdir(source_dir):
                if filename.endswith(".mp4"):
                    source_file = os.path.join(source_dir, filename)
                    target_dir = os.path.join(target_base_dir, seq_dir, "frames")
                    # 确保目标目录存在
                    os.makedirs(target_dir, exist_ok=True)
                    # 复制 MP4 文件到目标目录
                    # target_file = os.path.join(target_dir, filename)
                    vedio_image_sig(source_file, target_dir)


